package org.rkuk.kasutil.media 
{
	/**
	 * ...
	 * @author rkuk
	 */
	internal class BufferState extends PauseState 
	{
		private var isPausing:Boolean;
		public function BufferState(media:MediaProxy, isSeeking:Boolean)
		{
			super(media, isSeeking);
			isPausing = false;
			initStateListener();
		}
		
		/**
		 * 进入当前状态时，在没有操作的情况下就需要立即征听MediaProxy的stop和buffer事件
		 */
		private function initStateListener():void 
		{
			if (media.isBuffering)
				media.addEventListener(MediaStreamStatusEvent.STATUS_PLAY, onMediaResume);
			else//网速较快的时候，可能不会收到NetStream.Buffer.Full
				onMediaResume(null);
		}
		
		/**
		 * @inheritDoc
		 */
		override public function get description():String 
		{
			return MediaSourceEvent.BUFFER;
		}
		
		/**
		 * @inheritDoc
		 */
		override public function dispose():void 
		{
			if (media.hasEventListener(MediaStreamStatusEvent.STATUS_PAUSE))
				media.removeEventListener(MediaStreamStatusEvent.STATUS_PAUSE, onMediaPause);
				
			super.dispose();
		}
		
		/**
		 * @inheritDoc
		 * 在BufferState中，resume命令不起作用，所以重载PauseState中的Resume方法
		 */
		override public function resume():void 
		{
			
		}
		
		/**
		 * @inheritDoc
		 */
		override public function start(...rest):void 
		{
			if (!isPlayingOrStopping && media.hasEventListener(MediaStreamStatusEvent.STATUS_PAUSE))
				media.removeEventListener(MediaStreamStatusEvent.STATUS_PAUSE, onMediaPause);
					
			//super.start中会自己判断执行的条件
			super.start.apply(this, rest);
		}
		
		/**
		 * @inheritDoc
		 */
		override public function stop():void 
		{
			if (!isPlayingOrStopping && media.hasEventListener(MediaStreamStatusEvent.STATUS_PAUSE))
				media.removeEventListener(MediaStreamStatusEvent.STATUS_PAUSE, onMediaPause);
					
			//super.stop中会自己判断执行的条件
			super.stop();
		}
		
		/**
		 * @inheritDoc
		 */
		override public function pause():void 
		{
			if (!isPausing && !isPlayingOrStopping)
			{
				isPausing = true;
				media.addEventListener(MediaStreamStatusEvent.STATUS_PAUSE, onMediaPause);
				media.pause();
			}
		}
		
		private function onMediaPause(e:MediaStreamStatusEvent):void 
		{
			var media:MediaProxy = this.media;
			dispose();
			
			media.state = new PauseState(media, isSeeking);
		}
	}
}